<?php
class CF_Storage_Ini extends CF_Storage_Array
{
	/**
	 * 
	 * @var string
	 */
	protected $_sectionDelim = ':';
	
	/**
	 * 
	 * @var string
	 */
	protected $_nestDelim = '.';
	
	/**
	 * 
	 * @param string $iniFile
	 * @param string $section [optional]
	 * @return void
	 * @throws CF_Reader_Exception
	 */
	public function __construct($iniFile, $section = null, $readOnly = true)
	{
		$data = @parse_ini_file($iniFile, true);
		
		if(!$data){
			throw new CF_Storage_Ini_Exception('Can\'t load ini file');
		}
		
		if(null === $section){
			$section = 'default';
			$data = array('default' => $data);
		}
		
		$data = $this->_parseData($data);
		if(null !== $section) $data = $data[$section];
		
		parent::__construct($data, $readOnly);
	}
	
	/**
	 * 
	 * @param array $data
	 * @return array
	 */
	protected function _parseData(array $data)
	{
		$jsonStorage = array();
		
		foreach($data as $section => $value){
			$section = explode($this->_sectionDelim, preg_replace('/\s+/', '', $section));
			$part = array();
			foreach ($value as $k => $v){
				$count = substr_count($k, $this->_nestDelim);
				$json = '{"' . str_replace($this->_nestDelim, '":{"', $k) . '":"' . $v . '"' . str_repeat('}', $count + 1);
				$part[$k] = $json;
			}
			$jsonStorage[$section[0]] = $part;
			if(isset($section[1])) $jsonStorage[$section[0]][';extend'] = $section[1];
		}
		
		$storage = array();
		foreach($jsonStorage as $section => &$value){
			if(isset($value[';extend'])){
				$value = array_merge($jsonStorage[$value[';extend']], $value);
			}
			unset($value[';extend']);
			$part = array();
			foreach($value as $k => $v){
				$part = array_merge_recursive($part, json_decode($v, true));
			}
			$storage[$section] = $part;
		}

		return $storage;
	}
}